﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusClustering.Dao
{
    class BusTrackingDao
    {
        public BusDataDataContext db = null;

        public BusTrackingDao()
        {
            db = new BusDataDataContext();
        }

        public void Insert(BusTracking newTracking)
        {
            try
            {
                
                db.BusTrackings.InsertOnSubmit(newTracking);
                db.SubmitChanges();
                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public List<BusTracking> LoadDatabase()
        {
            return db.BusTrackings.ToList();
        }

        public List<BusTracking> LoadTrackingListWithTimePoint(int year, int month, int day, int hour, int minute, int second, int minBound)
        {
            DateTime pointTime = new DateTime(year, month, day, hour, minute, second);
            TimeSpan tsLowerBound = new TimeSpan(0, minBound,0);
            TimeSpan tsUpperBound = new TimeSpan(0, 0, 59);
            DateTime upperBound = pointTime.Add(tsUpperBound);
            DateTime lowerBound = pointTime.Subtract(tsLowerBound);
            return db.BusTrackings.Where(t => t.TrackingTime >= lowerBound && t.TrackingTime <= upperBound).OrderByDescending(t => t.TrackingTime).ToList();
        }

        public List<BusTracking> LoadTrackingListWithTimePeriodAndDeviceId(int deviceId, DateTime timeFrom, DateTime timeTo)
        {
            return db.BusTrackings.Where(t => t.TrackingTime >= timeFrom && t.TrackingTime <= timeTo && t.DeviceId == deviceId).OrderByDescending(t => t.TrackingTime).ToList();
        }
    }
}
